//
//  GLImageDrawable.m
//  LMPhotoVideoSDK
//
//  Created by Aimar on 16/7/19.
//  Copyright © 2016年 魁钺会. All rights reserved.
//

#import "GLImageDrawable.h"
#import "GLRectangleSurface.h"
#import "GLTexture.h"
#import "GLShaderHelper.h"

@interface GLImageDrawable ()

@end

@implementation GLImageDrawable

- (id)initWithSize:(CGSize)size image:(UIImage*)image {
    self = [super init];
    if (self) {
        self.size = vec2(size.width, size.height);
        self.surface = [[GLRectangleSurface alloc] initWithSize:size];
        self.texture = [GLTexture createTextureWithUIImage:image];
        self.shader = [[GLShaderHelper shareInstance] getPresetShader:GLPresetShaderType_NormalTexture];
    }
    
    return self;
}

- (void)onDraw:(GLCanvas*)canvas {
    GLTextureShader* shader = (GLTextureShader *)canvas.effectShader;
    if (shader == nil) {
        shader = self.shader;
    }
    
    if (!shader.bind) {
        NSLog(@"bind shader fail! - %@", self);
    }
    
    glEnable(GL_TEXTURE_2D);
    if (!self.texture.bind) {
        NSLog(@"bind texture fail! - %@", self);
    }
    
    [shader setProjectionMatrix:[canvas projection]];
    [shader setModelViewMatrix:[canvas currentMatrix]];
    [shader setPosition:[self.surface getVertices] component:3];
    if ([self.shader isKindOfClass:[GLTextureShader class]]) {
        [shader setTextureCoord:[self.surface getTexcoords] component:2];
    }
    
    glDrawElements(GL_TRIANGLE_STRIP, [self.surface getIndexCount], GL_UNSIGNED_SHORT, [self.surface getIndices]);
}

@end
